package com.example.spring.exercise.controller;

import com.example.spring.exercise.service.dto.StudentDTO;
import com.example.spring.exercise.service.dto.StudentParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : zhayh
 * @date : 2021-3-29 21:23
 * @description : 第二单元的练习
 */
@Api(tags = "第2单元的API")
@RestController
@RequestMapping("/api/springmvc")
public class Unit2Controller {
    @ApiOperation(value = "使用路径参数与查询参数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "studentCode", paramType = "path", value = "学号",
                    dataTypeClass = String.class, required = true),
            @ApiImplicitParam(name = "studentName", paramType = "query", value = "姓名",
                    dataTypeClass = String.class, required = true)
    })
    @GetMapping("/student/{studentCode}")
    public ResponseEntity<StudentDTO> getStudent(@PathVariable String studentCode,
                                                 @RequestParam String studentName) {
        StudentDTO result = StudentDTO.builder()
                .studentCode(studentCode)
                .studentName(studentName)
                .build();
        return ResponseEntity.ok(result);
    }

    @ApiOperation(value = "使用body参数")
    @PostMapping("/body")
    public ResponseEntity<StudentDTO> addStudent(@RequestBody StudentParam studentParam) {
        return ResponseEntity.ok(studentParam.getStudentDTO());
    }

    @GetMapping("/student/{code}")
    public ResponseEntity<StudentDTO> getByCode(@PathVariable String code) throws Exception {
        List<StudentDTO> result = StudentDTO.students.stream().filter(studentDTO -> {
            return studentDTO.getStudentCode().equals(code);
        }).collect(Collectors.toList());
        if (result.size() == 0) {
            throw new Exception("未找到此学号的学生");
        }
        return ResponseEntity.ok(result.get(0));
    }
}
